package com.xingkeduo.service.consume.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xingkeduo.feign.ManageUserFeignService;
import com.xingkeduo.model.param.MarketingParam.MarketingReceiveTypeEnum;
import com.xingkeduo.service.consume.UserService;

@Service
public class UserServiceImpl implements UserService {
	Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	@Autowired
	ManageUserFeignService manageUserFeignService;

	@Override
	@Cacheable(value = "cache:marketing:queryUserIdsByMobileOrId", key = "#userParam")
	public List<Long> queryUserIdsByMobileOrId(String userParam) {
		try {
			String result = manageUserFeignService.queryUserByNameOrMobileOrId("{\"condition\":\"" + userParam + "\"}");
			JSONObject userListJson = JSON.parseObject(result);
			logger.info("userListJson:" + userListJson);
			String resultStatus = userListJson.getOrDefault("status", "0") == null ? "0"
					: userListJson.getOrDefault("status", "0").toString();
			if (resultStatus.equals("0")) {
				return Lists.newArrayList(0l);
			}
			JSONArray resultDataArray = userListJson.getJSONArray("data");
			if (resultDataArray == null || resultDataArray.isEmpty()) {
				return Lists.newArrayList(0l);
			}
			List<Long> newUserIdList = resultDataArray.stream()
					.map(json -> Long.parseLong(((Map<String, Object>) json).getOrDefault("id", "0").toString()))
					.collect(Collectors.toList());
			return newUserIdList;
		} catch (Exception e) {
			logger.error("【用户查询】根据用户id或手机号查询用户失败,e:{}", e);
			return Lists.newArrayList(0l);
		}
	}

	@Override
	@Cacheable(value = "cache:marketing:queryUserIdsByUserId", key = "#userId")
	public List<Long> queryUserIdsByUserId(Long userId) {
		try {
			if (userId == null) {
				return Lists.newArrayList(0l);
			}
			String userListStr = manageUserFeignService.queryUserListByUserId("{\"id\":" + userId + "}");
			if (StringUtils.isBlank(userListStr)) {
				return Lists.newArrayList(userId);
			}
			JSONObject message = JSON.parseObject(userListStr);
			String status = message.getOrDefault("status", "0") == null ? "0"
					: message.getOrDefault("status", "0").toString();
			if ("0".equals(status)) {
				return Lists.newArrayList(userId);
			}
			JSONArray array = message.getObject("data", JSONArray.class);
			if (array == null || array.isEmpty()) {
				return Lists.newArrayList(userId);
			}
			List<Long> userList = array.toJavaList(Long.class);
			if (CollectionUtils.isEmpty(userList)) {
				return Lists.newArrayList(userId);
			}
			if (!userList.contains(userId)) {
				userList.add(userId);
			}
			return userList;
		} catch (Exception e) {
			logger.error("【用户查询】根据用户ID查询用户集合失败,e:{}", e);
			return Lists.newArrayList(userId);
		}
	}

	@Override
	@Cacheable(value = "cache:marketing:queryOnlyUserInfosByUserId", key = "#userId")
	public Map<String, String> queryOnlyUserInfosByUserId(Long userId) {
		try {
			Map<String, String> returnMap = Maps.newHashMap();
			if (userId == null) {
				returnMap.put("id", "0");
				return returnMap;
			}
			returnMap.put("id", userId.toString());
			String result = manageUserFeignService.queryUserByNameOrMobileOrId("{\"condition\":\"" + userId + "\"}");
			JSONObject userListJson = JSON.parseObject(result);
			logger.info("userId:{},queryOnlyUserInfosByUserId==userListJson:{}", userId, userListJson);
			String resultStatus = userListJson.getOrDefault("status", "0") == null ? "0"
					: userListJson.getOrDefault("status", "0").toString();
			if (resultStatus.equals("0")) {
				return returnMap;
			}
			JSONArray resultDataArray = userListJson.getJSONArray("data");
			if (resultDataArray == null || resultDataArray.isEmpty()) {
				return returnMap;
			}
			int size = resultDataArray.size();
			for (int i = 0; i < size; i++) {
				JSONObject resultData = resultDataArray.getJSONObject(i);
				String oldUserId = resultData.getOrDefault("id", "0") == null ? "0"
						: resultData.getOrDefault("id", "0").toString();
				if (userId.equals(Long.parseLong(oldUserId))) {
					returnMap.put("name", resultData.getOrDefault("name", "") == null ? ""
							: resultData.getOrDefault("name", "").toString());
					returnMap.put("phone", resultData.getOrDefault("phone", "") == null ? ""
							: resultData.getOrDefault("phone", "").toString());
					return returnMap;
				}
			}
			return returnMap;
		} catch (Exception e) {
			logger.error("【用户查询】根据用户id查询用户详情失败,e:{}", e);
			Map<String, String> returnMap = Maps.newHashMap();
			if (userId == null) {
				returnMap.put("id", "0");
				return returnMap;
			}
			return returnMap;
		}
	}

	@Override
	@Cacheable(value = "cache:marketing:queryCraftsmanById", key = "#hairStyleServiceId")
	public Map<String, String> queryCraftsmanById(Long hairStyleServiceId) {
		try {
			Map<String, String> returnMap = Maps.newHashMap();
			if (hairStyleServiceId == null) {
				returnMap.put("id", "0");
				return returnMap;
			}
			returnMap.put("id", hairStyleServiceId + "");
			String result = manageUserFeignService.queryCraftsmanById(JSON.toJSONString(returnMap));
			JSONObject userJson = JSON.parseObject(result);
			logger.info("queryCraftsmanById==hairStyleServiceJson:" + userJson);
			String resultStatus = userJson.getOrDefault("status", "0") == null ? "0"
					: userJson.getOrDefault("status", "0").toString();
			if (resultStatus.equals("0")) {
				return Maps.newHashMap();
			}
			JSONObject resultDateJson = userJson.getJSONObject("data");
			if (resultDateJson == null) {
				return Maps.newHashMap();
			}
			returnMap.put("name", resultDateJson.getOrDefault("name", "") == null ? ""
					: resultDateJson.getOrDefault("name", "").toString());
			return returnMap;
		} catch (Exception e) {
			logger.error("【发型师查询】根据发型师id查询发型师详情失败,e:{}", e);
			Map<String, String> returnMap = Maps.newHashMap();
			if (hairStyleServiceId == null) {
				returnMap.put("id", "0");
				return returnMap;
			}
			return returnMap;
		}
	}

	@Override
	public Integer verifyIsNewUser(Long userId) {
		try {
			if (userId == null) {
				return MarketingReceiveTypeEnum.ALL.getCode();
			}
			HashMap<String, String> map = new HashMap<>();
			map.put("id", userId.toString());
			String result = manageUserFeignService.verifyIsNewUser(JSON.toJSONString(map));
			JSONObject userJson = JSON.parseObject(result);
			logger.info("verifyIsNewUser:" + userJson);
			String resultStatus = userJson.getOrDefault("status", "0") == null ? "0"
					: userJson.getOrDefault("status", "0").toString();
			if (resultStatus.equals("0")) {
				return MarketingReceiveTypeEnum.ALL.getCode();
			}
			Boolean resultDateBoolean = userJson.getBoolean("data");
			if (resultDateBoolean == null) {
				return MarketingReceiveTypeEnum.ALL.getCode();
			}
			return resultDateBoolean ? MarketingReceiveTypeEnum.PLATFORM_NEW.getCode()
					: MarketingReceiveTypeEnum.ALL.getCode();

		} catch (Exception e) {
			logger.error("【用户查询】验证是否是新用户失败,e:{}", e);
			return MarketingReceiveTypeEnum.ALL.getCode();
		}
	}

}
